module.exports = {
  async getExamResult(recordId) {
    try {
      if (!recordId) {
        return {
          code: -1,
          message: '缺少记录ID'
        };
      }

      const db = uniCloud.database();
      
      // 获取考试记录
      const examRecord = await db.collection('exam_records')
        .doc(recordId)
        .get()
        .then(res => res.data[0]);

      console.log('获取到的考试记录:', examRecord);

      if (!examRecord) {
        return {
          code: -1,
          message: '考试记录不存在'
        };
      }

      // 获取考试信息
      const examInfo = await db.collection('exam_papers')
        .doc(examRecord.exam_id)
        .get()
        .then(res => res.data[0]);

      console.log('获取到的考试信息:', examInfo);

      // 处理题目数据
      let questions = [];
      
      // 1. 先尝试从考试详情获取题目
      if (examInfo && examInfo.questions && Array.isArray(examInfo.questions)) {
        console.log('从考试详情中获取题目');
        questions = examInfo.questions;
      } else {
        // 2. 如果没有，则从考试记录中获取
        if (examRecord.questions && Array.isArray(examRecord.questions)) {
          console.log('从考试记录中获取题目');
          questions = examRecord.questions;
        } else if (examRecord.answers && Array.isArray(examRecord.answers)) {
          // 3. 从答案恢复题目结构
          console.log('从答案中恢复题目结构');
          questions = examRecord.answers.map(answer => ({
            title: answer.question || '题目内容缺失',
            type: answer.type || 'single',
            options: answer.options || [],
            correct_answer: answer.correct_answer,
            ...answer
          }));
        }
      }

      // 如果没有找到题目，返回错误
      if (!questions || questions.length === 0) {
        console.error('未找到题目数据');
        return {
          code: -1,
          message: '无法获取题目数据'
        };
      }

      // 处理用户答案
      const processedQuestions = questions.map((question, index) => {
        const answer = examRecord.answers && examRecord.answers[index];
        return {
          content: question.title || question.content || '题目内容缺失',
          type: question.type || 'single',
          options: question.options || [],
          correct_answer: question.correct_answer || [],
          user_answer: answer ? (answer.user_answer || answer.answer || []) : [],
          is_correct: answer ? answer.is_correct : false,
          explanation: question.explanation || ''
        };
      });

      // 构建返回数据
      return {
        code: 0,
        data: {
          exam_id: examRecord.exam_id,
          title: examInfo?.title || examRecord.exam_title || '未命名考试',
          questions: processedQuestions,
          total_score: examRecord.total_score || 0,
          pass_score: examInfo?.pass_score || 60,
          user_score: examRecord.score || 0,
          submit_time: examRecord.submit_time,
          duration: examRecord.duration || 0
        }
      };
    } catch (error) {
      console.error('获取考试结果失败:', error);
      return {
        code: -1,
        message: error.message || '获取考试结果失败'
      };
    }
  },

  // 保存题目到数据库
  async saveQuestion(questionData) {
    try {
      if (!questionData) {
        return {
          code: -1,
          message: '题目数据不能为空'
        };
      }

      const db = uniCloud.database();
      
      // 构建题目数据
      const question = {
        title: questionData.title,
        type: questionData.type,
        options: questionData.options || [],
        correct_option: questionData.correct_option,
        correct_options: questionData.correct_options || [],
        explanation: questionData.explanation || '',
        score: questionData.score || 0,
        media_files: questionData.media_files || [],
        exam_id: questionData.exam_id,
        create_date: new Date(),
        update_date: new Date()
      };

      // 保存到 exam_questions 集合
      const result = await db.collection('exam_questions').add(question);
      
      if (result.id) {
        // 同时更新 exam_papers 集合中的题目引用
        await db.collection('exam_papers').doc(questionData.exam_id).update({
          questions: db.command.push([result.id])
        });

        return {
          code: 0,
          message: '保存成功',
          data: {
            question_id: result.id
          }
        };
      }

      return {
        code: -1,
        message: '保存失败'
      };
    } catch (error) {
      console.error('保存题目失败:', error);
      return {
        code: -1,
        message: error.message || '保存题目失败'
      };
    }
  },

  // 更新题目
  async updateQuestion(questionData) {
    try {
      if (!questionData || !questionData._id) {
        return {
          code: -1,
          message: '题目数据不完整'
        };
      }

      const db = uniCloud.database();
      
      // 更新题目数据
      const result = await db.collection('exam_questions')
        .doc(questionData._id)
        .update({
          title: questionData.title,
          type: questionData.type,
          options: questionData.options || [],
          correct_option: questionData.correct_option,
          correct_options: questionData.correct_options || [],
          explanation: questionData.explanation || '',
          score: questionData.score || 0,
          media_files: questionData.media_files || [],
          update_date: new Date()
        });

      if (result.updated === 1) {
        return {
          code: 0,
          message: '更新成功'
        };
      }

      return {
        code: -1,
        message: '更新失败'
      };
    } catch (error) {
      console.error('更新题目失败:', error);
      return {
        code: -1,
        message: error.message || '更新题目失败'
      };
    }
  }
}; 